package com.cqc.jdk8.Jtime;

import org.junit.Test;

import java.time.LocalDate;
import java.time.Period;
import java.time.chrono.IsoChronology;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;

/**
 * @author cui
 * @date 2024/6/29 21:08
 * @description
 **/
public class PeriodTest {
    /**
     * Period 计算2个日期间隔 天数、月数、年数
     */
    @Test
    public void f1() {
        LocalDate date1 = LocalDate.of(2022, 12, 30);
        LocalDate date2 = LocalDate.parse("2023-02-05", DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        //Period只能同单位比较。如年与年的差距，月与月的差距，天与天的差距，而不是2个日期间隔的天数
        Period period = Period.between(date1, date2);
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();//
        long days2 = period.get(ChronoUnit.DAYS);
        //years=0, months=1, days=6, days2=6
        System.out.println("years=" + years + ", months=" + months + ", days=" + days + ", days2=" + days2);

        List<TemporalUnit> units = period.getUnits();
        IsoChronology chronology = period.getChronology();

        //方法2: 用 ChronoUnit 计算间隔
        //开始日期和结束日期，只能算1个。也就是今天和昨天差1天，而不是2天)
        long year = ChronoUnit.YEARS.between(date1, date2);
        long month = ChronoUnit.MONTHS.between(date1, date2);
        long day = ChronoUnit.DAYS.between(date1, date2);
        long week = ChronoUnit.WEEKS.between(date1, date2);
        //year=0, month=1, day=37=1+31+5, week=5
        System.out.println("year=" + year + ", month=" + month + ", day=" + day + ", week=" + week);

    }
}
